/**
 * @see https://umijs.org/zh-CN/plugins/plugin-access
 * */

export default function access(initialState: { currentUser?: API.CurrentUser } | undefined) {
  const { perms, roles } = initialState ?? {};
  const isAdmin = roles?.includes('ROLE_ADMIN');
  const access: { [key: string]: any } = {
    canAdmin: isAdmin,
    can: (perm: string): boolean => {
      if (isAdmin) {
        return true;
      }
      return perms?.includes(perm);
    },
    // 计算入参中符合权限的个数
    calcPermsLen: (targetPerms: string[]): number => {
      let len = 0;
      if (isAdmin) {
        return targetPerms?.length;
      }
      (targetPerms || []).forEach((item) => {
        if (perms?.includes(item)) {
          len += 1;
        }
      });
      return len;
    },
  };
  if (Array.isArray(perms)) {
    perms.forEach((item: string) => {
      access[item] = true;
    });
  }
  return access;
}
